package main

import (
	"context"
	_ "embed"
	"strings"

	"github.com/samber/lo"

	"github.com/glennliao/apijson-go"
	_ "github.com/glennliao/apijson-go/drivers/goframe"
	"github.com/glennliao/apijson-go/drivers/goframe/web"
	"github.com/glennliao/bookmark/app"
	_ "github.com/glennliao/bookmark/packed"
	_ "github.com/gogf/gf/contrib/drivers/mysql/v2"
	_ "github.com/gogf/gf/contrib/drivers/sqlite/v2"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcmd"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/gfile"
	"github.com/gogf/gf/v2/util/grand"
)

//go:embed config.yaml.example
var 配置示例 string

var (
	主命令 = &gcmd.Command{
		Name:        "server",
		Brief:       "启动HTTP服务",
		Description: "",
		Func: func(上下文 context.Context, 解析器 *gcmd.Parser) (错误 error) {

			// 数据库同步前判断
			数据表列表, 错误 := g.DB().Tables(上下文)
			if 错误 != nil {
				g.Log().Fatal(上下文, 错误)
			}

			apiJson实例 := apijson.J加载(app.App)

			网页处理器 := web.X新建GF(apiJson实例)

			服务器 := g.Server()

			服务器.Group("/api", func(路由组 *ghttp.RouterGroup) {
				路由组.Middleware(app.K跨域中间件, app.X响应中间件, app.R认证中间件)
				路由组.Bind(app.J接口结构体{
					API实例: apiJson实例,
				})
			})

			服务器.Group("/api/data", func(路由组 *ghttp.RouterGroup) {
				路由组.Middleware(app.K跨域中间件, app.R认证中间件)
				网页处理器.B绑定路由(路由组)
			})

			if g.Res().Contains("dist") {
				服务器.AddStaticPath("/", "dist")
				服务器.AddStaticPath("/assets", "dist/assets")
			}

			if !lo.Contains(数据表列表, "config") && lo.Contains(数据表列表, "group_bookmark") {
				app.S升级到v0_11(上下文)
			}

			服务器.Run()
			return nil
		},
	}

	初始化命令 = &gcmd.Command{
		Name:        "init",
		Brief:       "初始化配置文件",
		Description: "",
		Func: func(上下文 context.Context, 解析器 *gcmd.Parser) (错误 error) {
			if !gfile.Exists("config.yaml") {
				配置示例 = strings.Replace(配置示例, "{{secret}}", grand.S(32), 1)

				gfile.PutContents("config.yaml", 配置示例)
			}
			return
		},
	}
)

func main() {
	错误 := 主命令.AddCommand(初始化命令)
	if 错误 != nil {
		panic(错误)
	}
	主命令.Run(gctx.New())
}
